import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Layout, Input, Button, Table, Modal, Pagination } from 'antd';
import { DEFAULT_PAGE_SIZE } from '@/constants'
import styles from './index.less';

import Edit from './edit';

const { Content } = Layout;
const { confirm } = Modal;

class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.modularName = 'menu';
    this.state = {
      query: {}
    }
  }

  componentDidMount() {
    this.props.dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        current: 1,
        pageSize: DEFAULT_PAGE_SIZE
      }
    });
  }

  componentWillUnmount() {
    this.props.dispatch({ type: `${this.modularName}/clear` });
  }

  appendBtnClick = () => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '新增资源', editData: {} }
    })
  }

  authorizeBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '权限授权', editData: { ...record } },
    });
  }

  editBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '编辑资源', editData: { ...record } }
    })
  }

  stopBtnClick = (record) => {
    confirm({
      title: '是否确认删除资源?',
      content: Array.isArray(record) ? undefined : `资源 [${record.name}]`,
      onOk: () => {
        const { dispatch, modular } = this.props;
        const { rowKey, filterValue, current = 1, pageSize = DEFAULT_PAGE_SIZE } = modular;

        dispatch({
          type: `${this.modularName}/deleteData`,
          payload: {
            [rowKey]: record[rowKey],
            value: filterValue,
            current,
            pageSize
          }
        });
      },
      onCancel() { },
    });
  }

  searchBtnClick = () => {
    const { query = {} } = this.state;
    const { dispatch, modular } = this.props;
    const { data = [], current = 1, pageSize = DEFAULT_PAGE_SIZE } = modular;

    dispatch({
      type: `${this.modularName}/filter`,
      payload: {
        value: query.keyword,
        data,
        current: 1,
        pageSize
      }
    });
  }

  onChange = (current, pageSize) => {
    const { dispatch } = this.props;

    dispatch({
      type: `${this.modularName}/changeState`,
      payload: {
        current,
        pageSize
      }
    })
  }

  onShowSizeChange = (current, pageSize) => {
    this.onChange(1, pageSize)
  }

  onOk = () => {
    const { dispatch, form, modular } = this.props;
    const { filterValue, current, pageSize, editData = {} } = modular;

    form.validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: `${this.modularName}/saveOrUpdateData`,
          payload: {
            data: {
              ...editData,
              ...values
            },
            value: filterValue,
            current,
            pageSize
          }
        });
      }
    });
  }

  render() {
    const { query = {} } = this.state;
    const { dispatch, form, loading, modular } = this.props;
    const { data = [], filterData = [], filterValue, rowKey, current = 1, pageSize = DEFAULT_PAGE_SIZE, total = 0, visible, editData = {} } = modular;
    const showData = total > pageSize ? (filterValue ? filterData : data).slice((current - 1) * pageSize, current * pageSize) : (filterValue ? filterData : data);

    const columns = [{
      title: '编码',
      dataIndex: 'code',
      ellipsis: true
    }, {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true
    }, {
      title: '类型',
      dataIndex: 'type',
      ellipsis: true,
      render: (text, record) => {
        if (text === '1') {
          return '菜单';
        } else if (text === '2') {
          return '按钮';
        } else if (text === '3') {
          return '资源';
        }
      }
    }, {
      title: '地址',
      dataIndex: 'uri',
      ellipsis: true
    }, {
      title: '操作',
      dataIndex: 'operate',
      align: 'center',
      width: 200,
      render: (text, record) => {
        return (
          <div className={styles.common_span_group}>
            <span onClick={this.editBtnClick.bind(this, record)}>编辑</span>
            <span style={{ color: '#ff4d4f' }} onClick={this.stopBtnClick.bind(this, record)}>删除</span>
          </div>
        );
      }
    }];

    return (
      <Layout className={styles.basic_layout_wrapper}>
        <div className={styles.conditions_wrapper}>
          <Input placeholder='按名称/编码搜索' style={{ width: 240, marginRight: 16 }} onChange={e => this.setState({ query: { ...query, keyword: e.target.value } })} />
          <Button icon='search' type='primary' onClick={this.searchBtnClick}>搜索</Button>
        </div>
        <Content className={styles.conditions_wrapper} style={{ margin: 0 }}>
          <Layout style={{ backgroundColor: 'transparent', height: '100%' }}>
            <div style={{ marginBottom: 16 }}>
              <Button icon='plus' type='primary' style={{ width: 110, marginRight: 16 }} onClick={this.appendBtnClick}>新增资源</Button>
            </div>
            <Content className={styles.common_table_wrapper}>
              <Table
                columns={columns}
                dataSource={showData}
                loading={!!loading.effects[`${this.modularName}/queryData`] || !!loading.effects[`${this.modularName}/deleteData`]}
                pagination={false}
                rowKey={rowKey}
              />
            </Content>
            <div style={{ marginTop: 16 }}>
              <Pagination
                current={current}
                pageSize={pageSize}
                total={total}
                showQuickJumper
                showSizeChanger
                showTotal={(total, range) => `共有 ${total} 条数据`}
                onChange={this.onChange}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          </Layout>
        </Content>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title={visible}
          visible={!!visible}
          wrapClassName={styles.common_modal_wrapper}
          width={visible === '权限授权' ? 840 : 560}
          onOk={this.onOk}
          onCancel={() => {
            dispatch({
              type: `${this.modularName}/changeState`,
              payload: {
                visible: undefined, editData: {}
              }
            })
          }}
        >
          <Edit form={form} data={editData} menus={data} />
        </Modal>
      </Layout>
    );
  }
}

export default connect(({ loading, menu }) => ({ loading, modular: menu }))(Form.create()(Index));